package com.youlai.system.controller;

import com.youlai.system.model.entity.FileInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.UUID;

@Tag(name = "336.Storage File to Local")
@RestController
@RequestMapping("/api/v1/local-files")
@RequiredArgsConstructor
public class LocalStorageFileController {


    @Value("${file.upload-dir}")
    private String uploadDir;


    // 上传图片
    @PostMapping
    public ResponseEntity<FileInfo> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        // 校验类型和大小
        String contentType = file.getContentType();
        if (!Arrays.asList("image/jpeg", "image/png", "image/gif", "image/webp").contains(contentType)) {
            return ResponseEntity.badRequest().build();
        }
        if (file.getSize() > 5 * 1024 * 1024) {
            return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE).build();
        }

        // 保存文件
        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        Path savePath = Paths.get(uploadDir, fileName);
        Files.createDirectories(savePath.getParent());
        file.transferTo(savePath);

        // 返回文件信息
        FileInfo info = new FileInfo();
        info.setName(file.getOriginalFilename());
        info.setUrl("/api/v1/files/download/" + fileName);
        return ResponseEntity.ok(info);
    }

    // 下载图片
    @GetMapping("/download/{fileName:.+}")
    public void downloadFile(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        Path filePath = Paths.get(uploadDir, fileName);
        if (!Files.exists(filePath)) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        response.setContentType(Files.probeContentType(filePath));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        Files.copy(filePath, response.getOutputStream());
        response.flushBuffer();
    }

    // 删除图片
    @DeleteMapping
    public ResponseEntity<Void> deleteFile(@RequestParam String filePath) {
        // filePath 传的是 url 字符串，需提取文件名
        String fileName = Paths.get(filePath).getFileName().toString();
        Path path = Paths.get(uploadDir, fileName);
        try {
            Files.deleteIfExists(path);
            return ResponseEntity.ok().build();
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
